//
//  WebServer.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2021/7/10.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLWebServer.h"
#import "NSURL+CLUtility.h"

@interface CLWebServer ()

@property (nonatomic, strong) GCDWebServer *server;

@end

@implementation CLWebServer

SYNTHESIZE_SINGLETON_FOR_CLASS(CLWebServer)

- (NSString *)base{
    return [NSString stringWithFormat:@"http://localhost:%lu",(unsigned long)_server.port];
}

- (instancetype)init{
    if (self = [super init]) {
        _server = [GCDWebServer new];
    }
    return self;
}

- (BOOL)start{
    if (!_server.isRunning) {
        [self.server startWithOptions:@{
                                        GCDWebServerOption_Port: @6800,
                                        GCDWebServerOption_BindToLocalhost: @YES,GCDWebServerOption_AutomaticallySuspendInBackground: @YES
                                        } error:NULL];
    }
    return _server.isRunning;
}

- (void)registerHandlerForMethod:(NSString *)method module:(NSString *)module resource:(NSString *)resource handler:(CLServerBlock)handler{
    NSParameterAssert(method);
    NSParameterAssert(module);
    NSParameterAssert(resource);
    NSParameterAssert(handler);
    
    CLServerBlock wrappedHandler = ^GCDWebServerResponse *(GCDWebServerRequest *request){
        if (![request.URL isLocal]) {
            return [[GCDWebServerResponse alloc] initWithStatusCode:403];
        }
        
        return handler(request);
    };
    
    [self.server addHandlerForMethod:method path:[NSString stringWithFormat:@"/%@/%@",module,resource] requestClass:[GCDWebServerRequest class] processBlock:wrappedHandler];
}

- (void)registerMainBundleResource:(NSString *)resource module:(NSString *)module{
    NSParameterAssert(resource);
    NSParameterAssert(module);
    
    NSString *path = [[NSBundle mainBundle] pathForResource:resource ofType:nil];
    [self.server addGETHandlerForPath:[NSString stringWithFormat:@"/%@/%@",module,resource.lastPathComponent] filePath:path isAttachment:NO cacheAge:UINT_MAX allowRangeRequests:YES];
}

@end
